import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

//Demo:示例
public class jdbcDemo1 {
    public static void main(String[] args) throws SQLException {
        //1.创建数据源(Datasource)对象
        Scanner scanner=new Scanner(System.in);
        DataSource dataSource=new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/117java?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");
        //2.和数据库服务器进行通信，需要建立网络链接
        Connection connection=dataSource.getConnection();
        //3.构造SQL语句
        System.out.println("请输入要插入的id: ");
        int id=scanner.nextInt();
        System.out.println("请输入要插入的name: ");
        String name=scanner.next();
        String sql="insert into student values(?,?)";
        PreparedStatement preparedStatement =connection.prepareStatement(sql);
        preparedStatement.setInt(1,id);
        preparedStatement.setString(2,name);
        //4.执行SQL(把sql通过网络发送到服务器)
        //进行增，删，该，甚至建表，删表.........这些操作统称为update~~
        //查，有另一个方法，executeQuery~~
        //当前的操作影响到几行，返回值是int类型~~
        int n =preparedStatement.executeUpdate();
        System.out.println("n="+n);
        //5.关闭连接等资源
        preparedStatement.close();
        connection.close();

    }
}
